from backend.services.base import BaseService
from backend.po.buy_order import BuyOrder
from backend.services.serializers import BuyOrderObjectSerializer
from backend.biz import BuyOrderBiz
from backend.services import SupplierService


class BuyOrderService(BaseService):
    def __init__(self):
        super().__init__(BuyOrder, BuyOrderObjectSerializer, BuyOrderBiz())
        self.supplier_svc = SupplierService()

    @staticmethod
    def __adapter_supplier(data):
        if data['supplier'] is None:
            data['supplier'] = 0
        else:
            data['supplier'] = data['supplier']['id']

    def preform_create(self, data, *args, **kwargs):
        self.__adapter_supplier(data)
        return super().preform_create(data, *args, **kwargs)

    def create(self, obj):
        if obj.supplier is not None and obj.supplier.id == 0:
            obj.supplier = self.supplier_svc.create(obj.supplier)

        return super().create(obj)

    def preform_update(self, data, *args, **kwargs):
        self.__adapter_supplier(data)
        return super().preform_update(data, *args, **kwargs)

    def update(self, obj):
        if obj.supplier is not None:
            if obj.supplier.id == 0:
                obj.supplier = self.supplier_svc.create(obj.supplier)
            else:
                self.supplier_svc.update(obj.supplier)

        return super().update(obj)
